/*
 * @(#)KeywordService.java $version 2012. 2. 8.
 *
 */

package com.mywep.myalimi.service;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.mywep.myalimi.common.DbConditionHolder;
import com.mywep.myalimi.model.Keyword;
import com.mywep.myalimi.model.User;
import com.mywep.myalimi.model.UserContent;
import com.mywep.myalimi.model.UserKeyword;
import com.mywep.myalimi.repository.content.UserContentRepository;
import com.mywep.myalimi.repository.keyword.KeywordRepository;
import com.mywep.myalimi.repository.keyword.UserKeywordRepository;

import com.nhncorp.lucy.spring.core.util.ExtendedMap;

/**
 * @author 한지웅
 */
@Service
public class UserKeywordService {
	private static final Logger LOG = LoggerFactory.getLogger(UserKeywordService.class);
	@Autowired
	private UserKeywordRepository userKeywordRepository;
	@Autowired
	private KeywordRepository keywordRepository;
	@Autowired
	private UserContentRepository userContentRepository;

	public int getTotalCountKeywords(String id) {
		ExtendedMap param = DbConditionHolder.getInstance();
		param.put("id", id);

		return userKeywordRepository.countByExample(param);
	}

	public List<UserKeyword> getKeywords(String id) {
		ExtendedMap param = DbConditionHolder.getInstance();
		param.put("id", id);

		return userKeywordRepository.selectByExample(param);
	}

	public void txAddKeyword(User user, String keywordStr) {
		UserKeyword userKeywordKey = new UserKeyword();
		userKeywordKey.setId(user.getId());
		userKeywordKey.setKeyword(keywordStr);
		userKeywordRepository.insert(userKeywordKey);

		Keyword keywordKey = new Keyword();
		keywordKey.setKeyword(keywordStr);
		Keyword keyword = keywordRepository.selectByPrimaryKey(keywordKey);
		if (keyword != null) {
			keywordKey.setCount(1);
			keywordRepository.updatePrimaryKey(keywordKey);
		} else {
			keywordRepository.insert(keywordKey);
		}
		
	}

	public void txDeleteKeyword(User user, int userKeywordKey, String keyword) {
		UserKeyword userKeywordParam = new UserKeyword();
		userKeywordParam.setUserKeywordKey(userKeywordKey);
		userKeywordRepository.delete(userKeywordParam);

		Keyword keywordParam = new Keyword();
		keywordParam.setKeyword(keyword);
		keywordParam.setCount(-1);
		keywordRepository.updatePrimaryKey(keywordParam);

		ExtendedMap userContentKey = DbConditionHolder.getInstance();
		userContentKey.put("id", user.getId());
		userContentKey.put("keyword", keyword);

		List<UserContent> userContents = userContentRepository.selectByExample(userContentKey);

		for (UserContent userContent : userContents) {
			userContentRepository.delete(userContent);
		}

	}

}
